package com.jd.share.bloom;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;

public class BloomFilterDemo {

	private static final int insertions = 100000000; // 100W

	public static void main(String[] args) {

		// 初始化一个存储string数据的布隆过滤器，初始化大小为100W
		BloomFilter<String> bf = BloomFilter.create(
				Funnels.stringFunnel(Charsets.UTF_8), insertions,0.003);

		Set<String> sets = new HashSet<String>(insertions);

		List<String> lists = new ArrayList<String>(insertions);

		// 向三个容器初始化100W个随机并且唯一的字符串
		for (int i = 0; i < insertions; i++) {
			String uuid = UUID.randomUUID().toString();
			bf.put(uuid);
			sets.add(uuid);
			lists.add(uuid);
		}
		
		int wrong = 0; // 错误判断的次数
		int right = 0; // 正确判断的次数
		
		for (int i = 0; i < 10000; i++) {

			String data = i % 100 == 0 ? lists.get(i / 100) : UUID.randomUUID()
					.toString();
			
			//有100个数据肯定是存在Bloom 里的    剩下的数据不存在
			if (bf.mightContain(data)) {
				if (sets.contains(data)) {
					//说存在 确实存在
					right++;
					continue;
				}
				//说存在   却不存在
				wrong++;
			}
			//说不存在  肯定不存在
			
		}
		
		System.out.println("====right===="+right);
		System.out.println("====wrong===="+wrong);

	}

}
